package com.xthh._function;

import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.net.Uri;
import android.nfc.NdefRecord;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Environment;
import android.os.Message;
import android.util.Base64;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.documentfile.provider.DocumentFile;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;

import com.google.zxing.WriterException;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;
import com.permissionx.guolindev.PermissionX;
import com.permissionx.guolindev.callback.RequestCallback;
import com.xt.xthh.R;
import com.xthh._enum.HH_EnumDeviceColorType;
import com.xthh._enum.HH_EnumFileType;
import com.xthh._enum.HH_EnumTextAlgin;
import com.xthh._function._ini.HH_INIBindDeviceInfo;
import com.xthh._function._ini.HH_INILoginInfo;
import com.xthh._function._zxing.HH_EncodingHandler;
import com.xthh._struct.HH_T_DIR_INFO;
import com.xthh._struct.HH_T_DeviceColorType;
import com.xthh._struct.HH_T_DeviceInfo;
import com.xthh._struct.HH_T_DeviceModel;
import com.xthh._struct.HH_T_LoginInfo;
import com.xthh._struct.HH_T_Material;
import com.xthh._struct.HH_T_ModelSize;
import com.xthh._struct.HH_T_PasterInfo;
import com.xthh._struct.HH_T_RGB;
import com.xthh._struct.HH_T_SystemParams;
import com.xthh._struct.HH_T_ThemeList;
import com.xthh.esl.BMPConverterUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class HH_SystemUtil {
    private static final String TAG = "XTHH_SystemUtil";
    private static final String FILE_SEP = "\t";// 写文件的拆分符号
    private static final String FILE_SEP_LINE_OVER = "\n";// 写文件的拆分符号

    public static boolean SendMessage(HH_T_SystemParams tp, int what, Object obj, int a1, int a2) {
        if (tp != null && tp.getHandler() != null) {
            Message msg1 = new Message();
            msg1.what = what;
            msg1.obj = obj;
            msg1.arg1 = a1;
            msg1.arg2 = a2;
            tp.getHandler().sendMessage(msg1);
            return true;
        } else {
            HH_Logging.i(TAG, tp, "SendMessage fail");
        }

        return false;
    }

    public static void Sleep(int ms) {
        try {
            Thread.sleep(ms);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    // 根据包名获取版本号
    private static PackageInfo GetPackageInfo(Context context) {
        PackageInfo pi = null;

        try {
            PackageManager pm = context.getPackageManager();
            pi = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_CONFIGURATIONS);

            return pi;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return pi;
    }

    public static String GetTempPath(HH_T_SystemParams tp, int index, HH_EnumFileType fileType){
        String packageName = tp.getApplication().getPackageName();
        packageName = packageName.replaceAll("\\.", "_");

        String rootDataDir = Environment.getExternalStorageDirectory().getPath();
        rootDataDir = rootDataDir + File.separator + "." + packageName;
        HH_FileUtil.CreateFolder(rootDataDir);
        rootDataDir = rootDataDir + File.separator + "temp";
        HH_FileUtil.CreateFolder(rootDataDir);
        rootDataDir = rootDataDir + File.separator + HH_TimeUtil.GetCurrentSystemTimeD();
        HH_FileUtil.CreateFolder(rootDataDir);
        rootDataDir = rootDataDir + File.separator + HH_TimeUtil.GetCurrentSystemTimeF() + "_" + Integer.toString(index);
        rootDataDir = rootDataDir + "." + fileType.toString();
        return rootDataDir;
    }

    // APP根目录 带\的
    public static String GetAppRootFolder(Application application){
        String packageName = application.getPackageName();
        packageName = packageName.replaceAll("\\.", "_");
        String rootDataDir = Environment.getExternalStorageDirectory().getPath();
        rootDataDir = rootDataDir + File.separator + "." + packageName;
        HH_FileUtil.CreateFolder(rootDataDir);
        rootDataDir = rootDataDir + File.separator;
        return rootDataDir;
    }

    public static String GetAppRootSaveFolder(Application application, String path){
        String packageName = application.getPackageName();
        packageName = packageName.replaceAll("\\.", "_");
        String rootDataDir = Environment.getExternalStorageDirectory().getPath();
        rootDataDir = rootDataDir + File.separator + "." + packageName;
        HH_FileUtil.CreateFolder(rootDataDir);
        rootDataDir = rootDataDir + File.separator;
        rootDataDir = rootDataDir + path;
        HH_FileUtil.CreateFolder(rootDataDir);
        rootDataDir = rootDataDir + File.separator;
        return rootDataDir;
    }

    public static String GetLogPath(){

        String rootDataDir = Environment.getExternalStorageDirectory().getPath();
        rootDataDir = rootDataDir + File.separator + "." + "xt";
        HH_FileUtil.CreateFolder(rootDataDir);
        rootDataDir = rootDataDir + File.separator + "log";
        HH_FileUtil.CreateFolder(rootDataDir);
        rootDataDir = rootDataDir + File.separator + HH_TimeUtil.GetCurrentSystemTimeD();
        HH_FileUtil.CreateFolder(rootDataDir);
        rootDataDir = rootDataDir + File.separator + HH_TimeUtil.GetCurrentSystemTimeH();
        rootDataDir = rootDataDir + "." + "txt";
        return rootDataDir;
    }


    public static String GetTempTaskInfoPath(Application application) {
        String path = GetAppRootFolder(application) + "log" + File.separator;
        path = path + "TASKINFOLOGS" + File.separator;
        HH_FileUtil.CreateFolder(path);
        path = path + HH_TimeUtil.GetCurrentSystemTimeD() + File.separator;
        HH_FileUtil.CreateFolder(path);
        return path;
    }


    // 根据包名获取版本名
    public static String GetAppVersionName(Context mContext, String packageName) {
        Context con = null;
        try {
            con = mContext.createPackageContext(packageName, Context.CONTEXT_IGNORE_SECURITY);
            return GetPackageInfo(con).versionName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
            return "";
        }
    }

    // 根据包名获取版本号
    public static int GetAppVersionCode(Context mContext, String packageName) {
        Context con = null;
        try {
            con = mContext.createPackageContext(packageName, Context.CONTEXT_IGNORE_SECURITY);
        } catch (NameNotFoundException e) {
            e.printStackTrace();
            return 0;
        }
        return GetPackageInfo(con).versionCode;
    }

    public static boolean IsAvilible(Context context, String packageName) {
        final PackageManager packageManager = context.getPackageManager();

        // 获取所有已安装程序的包信息
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        for (int i = 0; i < pinfo.size(); i++) {
            //Logging.WriteLog(TAG, "包名:" + pinfo.get(i).packageName);
            // 循环判断是否存在指定包名
            if (pinfo.get(i).packageName.equalsIgnoreCase(packageName)) {
                return true;
            }

        }
        return false;
    }


    public static boolean CheckIpAddress(String ip) {
        if (ip == null || ip.length() < 7)
            return false;

        String[] all = ip.split("\\.");
        if (all.length != 4)
            return false;

        for (int i = 0; i < 4; i++) {
            int m = HH_CharUtil.Atoi(all[i]);
            if (m < 0 || m > 255)
                return false;
        }

        return true;
    }

    // 检测包是不是在运行
    public static boolean IsAppRunning(Context context, String packageName) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(100);
        if (list.size() <= 0) {
            return false;
        }
        for (ActivityManager.RunningTaskInfo info : list) {
            if (info.baseActivity.getPackageName().equals(packageName)) {
                return true;
            }
        }
        return false;
    }

    // 运行包名
    public static void RunApp(Context ctx, String packageName) {
        PackageInfo pi;
        try {
            pi = ctx.getPackageManager().getPackageInfo(packageName, 0);
            Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
            // resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
            resolveIntent.setPackage(pi.packageName);
            PackageManager pManager = ctx.getPackageManager();
            List<ResolveInfo> apps = pManager.queryIntentActivities(resolveIntent, 0);

            ResolveInfo ri = apps.iterator().next();
            if (ri != null) {
                packageName = ri.activityInfo.packageName;
                String className = ri.activityInfo.name;

                Intent intent = new Intent(Intent.ACTION_MAIN);
                ComponentName cn = new ComponentName(packageName, className);

                intent.setComponent(cn);
                ctx.startActivity(intent);
            }
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }

    }

    public static String GetPhoneOperator(String src) {
        if (src == null || src.length() < 11)
            return "";

        int nSrcLen = src.length();

        // 去掉 +86 开头的手机号,例如要+8615920072211
        String tel = src.substring(nSrcLen - 11);
        if (tel == null || tel.length() != 11)
            return "";

        String tHead = tel.substring(0, 3);

        if (tHead.equals("134"))
            return "移动";
        if (tHead.equals("135"))
            return "移动";
        if (tHead.equals("136"))
            return "移动";
        if (tHead.equals("137"))
            return "移动";
        if (tHead.equals("138"))
            return "移动";
        if (tHead.equals("139"))
            return "移动";
        if (tHead.equals("147"))
            return "移动";
        if (tHead.equals("150"))
            return "移动";
        if (tHead.equals("151"))
            return "移动";
        if (tHead.equals("152"))
            return "移动";
        if (tHead.equals("157"))
            return "移动";
        if (tHead.equals("158"))
            return "移动";
        if (tHead.equals("159"))
            return "移动";
        if (tHead.equals("172"))
            return "移动";
        if (tHead.equals("178"))
            return "移动";
        if (tHead.equals("182"))
            return "移动";
        if (tHead.equals("183"))
            return "移动";
        if (tHead.equals("184"))
            return "移动";
        if (tHead.equals("187"))
            return "移动";
        if (tHead.equals("188"))
            return "移动";
        if (tHead.equals("195"))
            return "移动";
        if (tHead.equals("198"))
            return "移动";

        if (tHead.equals("130"))
            return "联通";
        if (tHead.equals("131"))
            return "联通";
        if (tHead.equals("132"))
            return "联通";
        if (tHead.equals("145"))
            return "联通";
        if (tHead.equals("155"))
            return "联通";
        if (tHead.equals("156"))
            return "联通";
        if (tHead.equals("166"))
            return "联通";
        if (tHead.equals("171"))
            return "联通";
        if (tHead.equals("175"))
            return "联通";
        if (tHead.equals("176"))
            return "联通";
        if (tHead.equals("185"))
            return "联通";
        if (tHead.equals("186"))
            return "联通";

        if (tHead.equals("133"))
            return "电信";
        if (tHead.equals("149"))
            return "电信";
        if (tHead.equals("153"))
            return "电信";
        if (tHead.equals("173"))
            return "电信";
        if (tHead.equals("177"))
            return "电信";
        if (tHead.equals("180"))
            return "电信";
        if (tHead.equals("181"))
            return "电信";
        if (tHead.equals("189"))
            return "电信";
        if (tHead.equals("191"))
            return "电信";
        if (tHead.equals("193"))
            return "电信";
        if (tHead.equals("199"))
            return "电信";
        return "";
    }

    public static int DeleteOldRecordFile(String path) {
        if (path == null)
            return -1;

        // 得到文件夹下面所有MP3文件
        List<String> listFiles = HH_FileUtil.SearchFiles(path, false);
        if (listFiles != null) {
            if (listFiles.size() == 0)
                return 0;
        }

        List<String> listTimeInfo = new ArrayList<String>();
        for (int i = 0; i < listFiles.size(); i++) {
            // record_20191204172719_35.mp3
            String src = listFiles.get(i);
            String ones[] = src.split("_");
            if (ones.length >= 3) {
                String sT = ones[ones.length - 2];
                listTimeInfo.add(sT);
            }
        }

        // 升序排序
        Collections.sort(listTimeInfo);

        if (listTimeInfo.size() <= 0)
            return 1;

        // 删除第0个
        for (int i = 0; i < listFiles.size(); i++) {
            String src = listFiles.get(i);
            if (src.indexOf(listTimeInfo.get(0)) >= 0) {
                File recordFile = new File(src);
                recordFile.delete();
                break;
            }
        }

        return 1;
    }

    public static void DelOtherWxFiles(String path, String ext) {
        File dir = new File(path);
        ListDeleteFile(dir, ext);
    }

    private static void ListDeleteFile(File dir, String ext) {
        File[] fileArray = dir.listFiles();
        if (fileArray != null) {
            for (File f : fileArray) {
                if (f.isFile() && f.getName().endsWith("." + ext)) {
                    // Logging.WriteLog(TAG, "del:" + f.getAbsolutePath());
                    HH_FileUtil.DeleteFile(f.getAbsolutePath());
                } else {
                    ListDeleteFile(f, ext);
                }
            }
        }
    }

    // 生成范围内的随机数
    public static int MadeRandom(int min, int max) {
        Random rand = new Random();
        return rand.nextInt(max - min + 1) + min;
    }

    /**
     * 检测是否有emoji表情
     *
     * @param source
     * @return
     */
    public static boolean ContainsEmoji(String source) {
        int len = source.length();
        for (int i = 0; i < len; i++) {
            char codePoint = source.charAt(i);
            if (!IsEmojiCharacter(codePoint)) { // 如果不能匹配,则该字符是Emoji表情
                return true;
            }
        }
        return false;
    }

    /**
     * 判断是否是Emoji
     *
     * @param codePoint 比较的单个字符
     * @return
     */
    public static boolean IsEmojiCharacter(char codePoint) {
        return (codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA) || (codePoint == 0xD) || ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) || ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) || ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF));
    }

    // 去掉无效字符
    public static String RemoveTheInvalidCharacter(String src) {
        String dst = "";
        for (int i = 0; i < src.length(); i++) {
            char codePoint = src.charAt(i);
            if (!IsEmojiCharacter(codePoint)) {
                dst += "";
            } else {
                dst += codePoint;
            }
        }

        return dst;
    }

    // LIST 字符串去重
    // 加锁
    public static synchronized List<String> RemoveDuplicate(List<String> srclist) {
        List<String> list = new ArrayList<String>();
        if (srclist != null) {
            for (String s : srclist)
                list.add(s);

            if (list.size() == 1) {
                return list;
            } else {
                Set set = new LinkedHashSet<String>();
                set.addAll(list);
                list.clear();
                list.addAll(set);
                return list;
            }
        } else {
            return null;
        }
    }

    // 生成发送的序列号
    public static String MadeSendSerial() {
        Calendar calendar = Calendar.getInstance();
        String year = String.format("%04d", calendar.get(Calendar.YEAR));
        String month = String.format("%02d", calendar.get(Calendar.MONTH) + 1);
        String day = String.format("%02d", calendar.get(Calendar.DAY_OF_MONTH));
        String hour = String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY));
        String minute = String.format("%02d", calendar.get(Calendar.MINUTE));
        String second = String.format("%02d", calendar.get(Calendar.SECOND));
        String mill = String.format("%03d", calendar.get(Calendar.MILLISECOND));

        return year + month + day + hour + minute + second + mill;
    }


    /**
     * 文件转base64字符串
     *
     * @param file
     * @return
     */
    public static String fileToBase64(File file) {
        String base64 = null;
        InputStream in = null;
        try {
            in = new FileInputStream(file);
            byte[] bytes = new byte[in.available()];
            int length = in.read(bytes);
            base64 = Base64.encodeToString(bytes, 0, length, Base64.DEFAULT);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return base64;
    }

    public static void SetClipData(String s, Context ctx) {
        if (s != null && s.length() > 0 && ctx != null) {
            ClipboardManager cm = (ClipboardManager) ctx.getSystemService(Context.CLIPBOARD_SERVICE);
            // 创建普通字符型ClipData
            ClipData mClipData = ClipData.newPlainText("Label", s);
            // 将ClipData内容放到系统剪贴板里。
            cm.setPrimaryClip(mClipData);
        }
    }


    public static byte[] compressBitmap(Bitmap bitmap) {
        ByteArrayOutputStream baos = null;
        try {
            baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            baos.close();
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            byte[] buffer = baos.toByteArray();
            BitmapFactory.decodeByteArray(buffer, 0, buffer.length, options);
            int outWidth = options.outWidth;
            int scale = 0;//outWidth / WIDTH;
            if (scale > 1) {
                options.inSampleSize = scale;
                options.inJustDecodeBounds = false;
                Bitmap tempBitmap = BitmapFactory.decodeByteArray(buffer, 0, buffer.length, options);
                baos = new ByteArrayOutputStream();
                tempBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                baos.close();
            }
            return baos.toByteArray();
        } catch (Exception e) {
            return null;
        } finally {
            try {
                if (baos != null) {
                    baos.close();
                }
            } catch (IOException e) {
                return null;
            }
        }
    }

    public static String MadeUnLockPwd() {
        Calendar calendar = Calendar.getInstance();
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        String hex = Integer.toHexString(hour * 10 + day).toLowerCase();

        return hex;
    }

    // 整数转2字节
    public static byte[] Variable16ToArray(long Variable) {
        byte[] array = new byte[2];
        array[0] = (byte) (Variable >> 8);
        array[1] = (byte) (Variable);

        return array;
    }

    // 整数转2字节
    public static byte[] Variable16ToArray(int Variable) {
        byte[] array = new byte[2];
        array[0] = (byte) (Variable >> 8);
        array[1] = (byte) (Variable);

        return array;
    }

    // 整数转4字节
    public static byte[] Variable32ToArray(long Variable) {
        byte[] array = new byte[4];
        array[0] = (byte) (Variable >> 24);
        array[1] = (byte) (Variable >> 16);
        array[2] = (byte) (Variable >> 8);
        array[3] = (byte) (Variable);
        return array;
    }


    // 整数转4字节
    public static byte[] Variable32ToArray(int Variable) {
        byte[] array = new byte[4];
        array[0] = (byte) (Variable >> 24);
        array[1] = (byte) (Variable >> 16);
        array[2] = (byte) (Variable >> 8);
        array[3] = (byte) (Variable);
        return array;
    }

    // list 转 数组
    public static byte[] ListToArray(List<Byte> list) {
        int nSize = list.size();
        ;
        byte[] array = new byte[nSize];
        for (int i = 0; i < nSize; i++) {
            array[i] = list.get(i);
        }
        return array;
    }

    /**
     * 按指定大小,分隔集合,将集合按规定个数分为n个部分
     *
     * @param list
     * @param len
     * @return
     */
    public static List<List<Integer>> splitList(List<Integer> list, int len) {
        if (list == null || list.size() == 0 || len < 1) {
            return null;
        }

        List<List<Integer>> result = new ArrayList<List<Integer>>();

        int size = list.size();
        int count = (size + len - 1) / len;

        for (int i = 0; i < count; i++) {
            List<Integer> subList = list.subList(i * len, ((i + 1) * len > size ? size : len * (i + 1)));
            result.add(subList);
        }
        return result;
    }


    // 定长拆分数组
    public static List<byte[]> SplitBytes(byte[] array, int num) {
        if (array == null || num <= 0)
            return null;

        int count = (array.length % num == 0) ? (array.length / num) : (array.length / num + 1);

        List<byte[]> arrayList = new ArrayList<>();

        for(int i=0;i<count;i++) {
            int index = i * num;

            byte[] list = new byte[num];
            if (i == count - 1){
                if (array.length % num > 0)
                    list = new byte[array.length % num];
            }

            int j = 0;
            while(j < num && index < array.length) {
                list[j] = array[index++];
                j++;
            }
            arrayList.add(list);
        }
        return arrayList;
    }


    // 获取分包数据
    public static List<List<Integer>> splitList(int[] data, int len) {

        if (data == null || data.length == 0 || len < 1)
            return null;

        List<List<Integer>> result = new ArrayList<List<Integer>>();

        int size = data.length;
        int count = (size + len - 1) / len;

        for (int i = 0; i < count; i++) {
            List<Integer> subList = new ArrayList<Integer>();
            for (int j = i * len; j < ((i + 1) * len > size ? size : len * (i + 1)); j++) {
                subList.add(data[j]);
            }
            result.add(subList);
        }
        return result;
    }

    // 获取真实文件名i
    public static String getRealFilePath(final Context context, final Uri fileUri) {

        if (context == null || fileUri == null)
            return null;
        DocumentFile documentFile = DocumentFile.fromSingleUri(context, fileUri);
        if (documentFile == null)
            return null;
        return documentFile.getName();
    }

    // 反转MAC地址
    // 将MAC地址前后换位置 ,例如19:E0:10:08:32:30 改为 30:32:08:10:0E:19
    public static String reverseMac(String mac) {
        String result = "";
        if (mac == null || mac.length() != 17)
            return mac;

        String[] temp = mac.split(":");
        if (temp.length == 6) {
            return temp[5] + ":" + temp[4] + ":" + temp[3] + ":" + temp[2] + ":" + temp[1] + ":" + temp[0];
        }

        return mac;
    }

    public static void MessageBox(Context context, String info) {
        Toast.makeText(context, info, Toast.LENGTH_SHORT).show();
    }



    public static HH_T_DIR_INFO GetPicPath(Context context, Uri uri) {
        HH_T_DIR_INFO diSrc;
        diSrc = HH_FileUtil.GetCurFileInfo(uri.getPath());
        if (diSrc.getExtN() != null && diSrc.getExtN().length() > 0) {
            return diSrc;
        } else {
            String sDstPath = HH_UriUtils.getFileAbsolutePath(context, uri);
            HH_T_DIR_INFO diDst = HH_FileUtil.GetCurFileInfo(sDstPath);
            return diDst;
        }
    }

    public static void FileSelectDialog(Activity act, int returnResult, int fileType) {

        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        switch (fileType) {
            case 0:
                intent.setType("*/*");
                break;
            case 1:
                intent.setType("image/*");
                break;
            default:
                intent.setType("*/*");
        }

        if (intent.resolveActivity(act.getPackageManager()) != null) {
            act.startActivityForResult(intent, returnResult);
        }
    }

    public static void FileSelectDialog(Fragment act, int returnResult, int fileType) {

        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        switch (fileType) {
            case 0:
                intent.setType("*/*");
                break;
            case 1:
                intent.setType("image/*");
                break;
            case 2:
                intent.setType("application/*");
                break;
            default:
                intent.setType("*/*");
        }

        act.startActivityForResult(intent, returnResult);

    }


    // 得到变色长椅模板XTE1632
    public static List<HH_T_DeviceModel> GetDiscolorationBenchModelsDefault(Context ctx) {
        List<HH_T_DeviceModel> list = new ArrayList<>();

       /* T_DeviceModel tbd4 = new T_DeviceModel();
        tbd4.setModelID("ID_BSCY_XTEKHI_0001");
        tbd4.setW(DATA.globa_n_bscy_device_width * DATA.globa_n_finalZoomMultiples);
        tbd4.setH(DATA.globa_n_bscy_device_height * DATA.globa_n_finalZoomMultiples);
      //  tbd4.setModelType(EnumModelType.BSCY);
        tbd4.setBscyData(new byte[]{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, (byte) 0x88, (byte) 0x88, (byte) 0x88, (byte) 0x8f, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x08, (byte) 0x88, (byte) 0x88, (byte) 0x88, (byte) 0x88, 0x00, 0x00, 0x00, 0x00, 0x00, (byte) 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x04, (byte) 0x80, 0x00, 0x08, (byte) 0x84, 0x00, 0x00, 0x00, 0x08, (byte) 0x9b, (byte) 0xee, (byte) 0xb8, (byte) 0x88, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x0f, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x03, 0x22, 0x23, 0x22, 0x23, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0x44, 0x44, 0x44, 0x44, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, (byte) 0x80, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x13, 0x6c, (byte) 0x8e, 0x31, 0x00, 0x00, 0x00, 0x08, (byte) 0xc4, 0x63, 0x11, 0x6c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00});
        Bitmap bitmap4 = PicUtils.GetBitmapFormBscyData(tbd4.getBscyData(), DATA.globa_n_bscy_device_width, DATA.globa_n_bscy_device_height, DATA.globa_n_finalZoomMultiples, ctx);

        //HH_SystemUtil.SaveTempFileToSD(bitmap4);

        tbd4.setListLayerInfo(GetLayerInfoFormBitmapBNSCY(bitmap4, DATA.globa_n_finalZoomMultiples));
        list.add(tbd4);

        // 这个数据,可以通过
        T_DeviceModel tbd5 = new T_DeviceModel();
        tbd5.setModelID("ID_BSCY_XTEKHI_0002");
        tbd5.setW(DATA.globa_n_bscy_device_width * DATA.globa_n_finalZoomMultiples);
        tbd5.setH(DATA.globa_n_bscy_device_height * DATA.globa_n_finalZoomMultiples);
       // tbd5.setModelType(EnumModelType.BSCY);
        tbd5.setBscyData(new int[]{0xf0, 0x88, 0x88, 0x88, 0x88, 0x00, 0x88, 0x00,
                0x00, 0x11, 0x11, 0x11, 0x11, 0x00, 0x11, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x00, 0x88, 0x08, 0x44, 0x20, 0xc0, 0x00, 0xe0,
                0x08, 0x88, 0x99, 0xba, 0xc8, 0xf8, 0x88, 0xf0,
                0x00, 0x88, 0x08, 0x44, 0x20, 0xf0, 0x00, 0xf0,
                0x00, 0x00, 0x11, 0x32, 0x40, 0x30, 0x00, 0x70,
                0x00, 0xe0, 0xc0, 0xe0, 0xcc, 0x4c, 0x44, 0xc0,
                0x02, 0xf2, 0xf2, 0xf0, 0xff, 0x0f, 0x00, 0x10,
                0x00, 0x38, 0x30, 0x30, 0x11, 0x15, 0x91, 0x10,
                0x02, 0x10, 0x07, 0x11, 0x11, 0x11, 0x11, 0x00,
                0x0c, 0x48, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x00,
                0x0f, 0x00, 0x12, 0x2f, 0x22, 0x22, 0x22, 0xe0,
                0x00, 0x23, 0xe2, 0x23, 0x44, 0xcc, 0x42, 0x00,
                0x01, 0x11, 0x72, 0x22, 0x22, 0x10, 0x12, 0x40,
                0x00, 0x0c, 0x44, 0x88, 0xc4, 0x42, 0x20, 0x00,
                0x08, 0x8f, 0x04, 0x44, 0x44, 0x44, 0x44, 0xc0,
                0x08, 0x91, 0x32, 0x41, 0x12, 0x26, 0x40, 0x10,
                0xf0, 0x11, 0x13, 0x55, 0x11, 0x11, 0x11, 0x10});
        Bitmap bitmap5 = PicUtils.GetBitmapFormBscyData(tbd5.getBscyData(), DATA.globa_n_bscy_device_width, DATA.globa_n_bscy_device_height, DATA.globa_n_finalZoomMultiples, ctx);
        tbd5.setListLayerInfo(GetLayerInfoFormBitmapBNSCY(bitmap5, DATA.globa_n_finalZoomMultiples));
        list.add(tbd5);

        T_DeviceModel tbd6 = new T_DeviceModel();
        tbd6.setModelID("ID_BSCY_XTEKHI_0003");
        tbd6.setW(DATA.globa_n_bscy_device_width * DATA.globa_n_finalZoomMultiples);
        tbd6.setH(DATA.globa_n_bscy_device_height * DATA.globa_n_finalZoomMultiples);
        //tbd6.setModelType(EnumModelType.BSCY);
        tbd6.setBscyData(new int[]{0x0c, 0x48, 0x00, 0xc0, 0x00, 0xc4, 0x44, 0x40, 0x0f, 0x01, 0x68, 0xf0, 0x00, 0xf4, 0x44, 0x40, 0x07, 0x00, 0x01, 0x70, 0x00, 0x70, 0x00, 0x00, 0x02, 0xa6, 0x0e, 0x2e, 0x02, 0xa6, 0x0a, 0xae, 0x03, 0x22, 0x03, 0x23, 0x03, 0x22, 0x02, 0x23, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00});
        Bitmap bitmap6 = PicUtils.GetBitmapFormBscyData(tbd6.getBscyData(), DATA.globa_n_bscy_device_width, DATA.globa_n_bscy_device_height, DATA.globa_n_finalZoomMultiples, ctx);
        tbd6.setListLayerInfo(GetLayerInfoFormBitmapBNSCY(bitmap6, DATA.globa_n_finalZoomMultiples));
        list.add(tbd6);

        T_DeviceModel tbd7 = new T_DeviceModel();
        tbd7.setModelID("ID_BSCY_XTEKHI_0007");
        tbd7.setW(DATA.globa_n_bscy_device_width * DATA.globa_n_finalZoomMultiples);
        tbd7.setH(DATA.globa_n_bscy_device_height * DATA.globa_n_finalZoomMultiples);
       // tbd7.setModelType(EnumModelType.BSCY);
        tbd7.setBscyData(new int[]{0x02,0xa6,0x0e,0x2e,0x02,0xa6,0x0a,0xae,0x0b,0x22,0x0b,0x2b,0x8b,0xa2,0x0a,0xab,0x00,0x1e,0x10,0x0f,0xaa,0x80,0x9a,0xa4,0x00,0xea,0xa2,0x0e,0xaa,0xe0,0xe2,0x2c,0x00,0x32,0x22,0x03,0x00,0x00,0x32,0x21,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00});
        Bitmap bitmap7 = PicUtils.GetBitmapFormBscyData(tbd7.getBscyData(), DATA.globa_n_bscy_device_width, DATA.globa_n_bscy_device_height, DATA.globa_n_finalZoomMultiples, ctx);
        tbd7.setListLayerInfo(GetLayerInfoFormBitmapBNSCY(bitmap7, DATA.globa_n_finalZoomMultiples));
        list.add(tbd7);
        */

        return list;
    }

    /*public static List<T_LayerInfo> GetLayerInfoFormBitmapBNSCY(Bitmap bitmap, int zoomMultiples) {
        List<T_LayerInfo> listLayerInfo = new ArrayList<>();
        // 这里已经是放大后的了,所以只是分出矩形就可以
        int x = 0;
        int y = 0;

        int nDataSrcWitdh = bitmap.getWidth() / zoomMultiples;
        int nDataSrcHeight = bitmap.getHeight() / zoomMultiples;

        for (int j = 0; j < nDataSrcHeight; j++) {
            for (int i = 0; i < nDataSrcWitdh; i++) {
                //Logging.i(TAG, "x = %d,y = %d", i * zoomMultiples, j * zoomMultiples);

                int pixel = bitmap.getPixel(i * zoomMultiples, j * zoomMultiples);
                int r = Color.red(pixel);
                int g = Color.green(pixel);
                int b = Color.blue(pixel);
                // Logging.i(TAG, "%d-%d-%d", r,g,b);

                T_LayerInfo tl = new T_LayerInfo(i * zoomMultiples, j * zoomMultiples, zoomMultiples, zoomMultiples, "SERIF", 8, r, g, b, EnumTextAlgin.LEFT, "");
                listLayerInfo.add(tl);
            }
        }

        return listLayerInfo;
    }*/


    private static void GetLineOneSereenData(byte[] data, int width, int height, byte[] bLine_0, byte[] bLine_1, byte[] bLine_2, byte[] bLine_3, byte[] bLine_4, byte[] bLine_5, byte[] bLine_6, byte[] bLine_7) {

        int index = 0;
        for (int m = width / 4 - 1; m >= 0; m--) {
            bLine_0[m] = data[index++];
            bLine_1[m] = data[index++];
            bLine_2[m] = data[index++];
            bLine_3[m] = data[index++];
            bLine_4[m] = data[index++];
            bLine_5[m] = data[index++];
            bLine_6[m] = data[index++];
            bLine_7[m] = data[index++];
        }
    }



    // 获取临时文件目录 后面是带/的
    public static String GetAppTempPath(Context ctx) {
        String rootDataDir = HH_FileUtil.GetStoragePath(ctx);
        String savePath = rootDataDir + File.separator;
        return savePath;
    }


    // 将版本号改为数字
    // // 检测是否有新版本 例如,当前是1.0.3,它的版本号就是1 * 10000 + 0 * 100 + 3;
    public static int GetCurrentVersion(String ver) {
        if (ver == null)
            return 0;

        String[] arraySrc = ver.split("\\.");
        if (arraySrc == null || arraySrc.length != 3)
            return 0;

        int n = 10000 * HH_CharUtil.Atoi(arraySrc[0]) + 100 * HH_CharUtil.Atoi(arraySrc[1]) + HH_CharUtil.Atoi(arraySrc[2]);

        return n;
    }




    public static String GetCurrentVer(int ver) {
        // 分别得到个位和10位
        int g = ver % 10;
        int s = ver % 100 / 10;// 十位
        int o = ver / 100;
        return String.format("%d.%d.%d", o, s, g);
    }

    public static HH_T_DeviceModel GetCurrentModel(String modelID, List<HH_T_DeviceModel> list) {
        if (modelID != null && modelID.length() > 0 && list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                if (HH_CharUtil.Strcmp(list.get(i).getModelID(), modelID, true)) {
                    return list.get(i);
                }
            }
        }
        return null;
    }

    // 返回，文本，黑白红  这些文本
    public static String GetDeviceColorTxtInfo(HH_EnumDeviceColorType type, List<HH_T_DeviceColorType> list) {
        if (list == null || type == null)
            return "";

        for (HH_T_DeviceColorType ct : list) {
            if (ct.getColorType() == type) {
                if (ct.getDeviceColorInfo() == null || ct.getDeviceColorInfo().length() <= 0)
                    return "";
                return ct.getDeviceColorInfo();
            }
        }

        return "";
    }

    public static String GetDeviceColorTypeInfo(Context ctx, HH_EnumDeviceColorType color){

        List<HH_T_DeviceColorType> list = HH_SystemUtil.InitDeviceColorTypeInfo(ctx);
        if (list != null){
            for (int i = 0; i < list.size(); i++){
                if (list.get(i).getColorType() == color)
                    return list.get(i).getDeviceColorInfo();
            }
        }
        return "";
    }


    public static Bitmap GetQrBitmap(String text, int width, HH_T_RGB bc) {

        Bitmap bitmapDemo = null;
        try {
            bitmapDemo = HH_EncodingHandler.createQRCode(text, width, bc);
            //String rootDataDir = IUtils.GetTempPath(".bmp");
            //PicUtils.BitmapSaveFile(bitmapDemo, rootDataDir);

        } catch (WriterException e) {
            e.printStackTrace();
        }

        return bitmapDemo;
    }


    // 判断一个字符是否是中文字符
    public static boolean isChinese(char c) {
        return c >= 0x4E00 && c <= 0x9FA5;// 根据字节码判断
    }

    // 判断一个字符串是否含有中文
    public static boolean isChinese(String str) {
        if (str == null)
            return false;
        for (char c : str.toCharArray()) {
            if (isChinese(c))
                return true;// 有一个中文字符就返回
        }
        return false;
    }


    /**
     * 显示键盘
     *
     * @param et 输入焦点
     */
    public static void showInput(final EditText et, Context ctx) {
        et.requestFocus();
        InputMethodManager imm = (InputMethodManager) ctx.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(et, InputMethodManager.SHOW_IMPLICIT);
    }

    /**
     * 隐藏键盘
     */
    public static void hideInput(Activity act, Context ctx) {
        InputMethodManager imm = (InputMethodManager) ctx.getSystemService(Context.INPUT_METHOD_SERVICE);
        View v = act.getWindow().peekDecorView();
        if (null != v) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }

    public static HH_T_ModelSize GetModelSizeFormInfo(String info) {

        HH_T_ModelSize modelSize = new HH_T_ModelSize(200, 200);

        if (info == null || info.length() <= 0)
            return modelSize;

        String[] split = info.split("\\*");
        if (split == null || split.length != 2)
            return modelSize;

        int w = HH_CharUtil.Atoi(split[0]);
        int h = HH_CharUtil.Atoi(split[1]);

        if (w <= 0 || h <= 0)
            return modelSize;

        modelSize = new HH_T_ModelSize(w, h);
        return modelSize;
    }

    public static HH_T_DeviceModel SetSingleColorType(HH_T_DeviceModel td) {

        HH_T_DeviceModel dst = td;
        dst.setSingleColor(false);

        String path = dst.getPicPath();
        if (path == null || !HH_FileUtil.IsExists(path))
            return dst;

        Bitmap bufferedImage = HH_PicUtils.GetBitmapFormFile(path);

        if (bufferedImage == null)
            return dst;

        int maxX = bufferedImage.getWidth();
        int maxY = bufferedImage.getHeight();
        List<Byte> pMyRgb = new ArrayList<Byte>();

        for (int i = 0; i < maxX; i++){
            for (int j = 0; j < maxY; j++){
                int pixel = bufferedImage.getPixel(i, j);
                int r = Color.red(pixel);
                int g = Color.green(pixel);
                int b = Color.blue(pixel);

                switch (dst.getDeviceColorType()){
                    case BLACK_WHITE_0:{
                        if (r == 0 && g == 0 && b == 0){

                        } else if (r == 255 && g == 255 && b == 255){

                        } else {
                            return dst;
                        }
                        break;
                    }
                    case BLACK_WHITE_YELLOW_1:{
                        if (r == 0 && g == 0 && b == 0){

                        } else if (r == 255 && g == 255 && b == 255){

                        } else if (r == 255 && g == 255 && b == 0){

                        } else {
                            return dst;
                        }
                        break;
                    }
                    case BLACK_WHITE_RED_2:{
                        if (r == 0 && g == 0 && b == 0){

                        } else if (r == 255 && g == 255 && b == 255){

                        } else if (r == 255 && g == 0 && b == 0){

                        } else {
                            return dst;
                        }
                        break;
                    }
                    case BLACK_WHITE_RED_YELLOW_3:{
                        if (r == 0 && g == 0 && b == 0){

                        } else if (r == 255 && g == 255 && b == 255){

                        } else if (r == 255 && g == 0 && b == 0){

                        } else if (r == 255 && g == 255 && b == 0){

                        } else {
                            return dst;
                        }
                        break;
                    }
                    case N_COLOR_4:{
                        if (r == 0 && g == 0 && b == 0){

                        } else if (r == 255 && g == 255 && b == 255){

                        } else if (r == 255 && g == 0 && b == 0){

                        } else if (r == 255 && g == 255 && b == 0){

                        }  else if (r == 0 && g == 255 && b == 0){

                        }  else if (r == 0 && g == 0 && b == 255){

                        }  else if (r == 255 && g == 127 && b == 0){

                        } else {
                            return dst;
                        }
                        break;
                    }

                    case E6_5:{
                        if (r == 0 && g == 0 && b == 0){

                        } else if (r == 255 && g == 255 && b == 255){

                        } else if (r == 255 && g == 0 && b == 0){

                        } else if (r == 255 && g == 255 && b == 0){

                        }  else if (r == 0 && g == 255 && b == 0){

                        }  else if (r == 0 && g == 0 && b == 255){

                        } else {
                            return dst;
                        }
                        break;
                    }
                    case NONE:{
                        return dst;
                    }
                }
            }
        }

        // 表明是纯色图
        int pixel = bufferedImage.getPixel(0, 0);
        dst.setSingleColor(true);
        dst.setBkgColor_r(Color.red(pixel));
        dst.setBkgColor_g(Color.green(pixel));
        dst.setBkgColor_b(Color.blue(pixel));

        return dst;
    }
    // #ff0000 转 rgb
    public static HH_T_RGB GetColor2(String str){
        HH_T_RGB t = new HH_T_RGB(255, 255, 255);

        if (str != null && str.length() == 7){
            byte []b = HH_HexUtil.hexStringToBytes(str.substring(1));
            if (b.length == 3){
                t.setR(b[0] & 0xff);
                t.setG(b[1] & 0xff);
                t.setB(b[2] & 0xff);
            }
        }

        return t;
    }

    public static void MadeTablePic(String path, int width, int height, int rows, int cols, int borderWidth, HH_T_RGB getColor2) {

        Bitmap bitmap = Bitmap.createBitmap(width, height,
                Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawColor(Color.WHITE);

        Paint paint = new Paint();
        paint.setStrokeWidth(borderWidth);//设置线宽
        paint.setAntiAlias(false);// 关掉抗锯齿
        paint.setStyle(Paint.Style.FILL); // 填充内部

        // 画四周
        canvas.drawLine(0, 0, width, borderWidth, paint);
        canvas.drawLine(0, 0, borderWidth, height, paint);
        canvas.drawLine(width - borderWidth, 0, width, height, paint);
        canvas.drawLine(0, height - borderWidth, width, height, paint);


        // 画横线
        if (rows > 1){  // 例高150，行数是3， 就是每一行是50高
            int tabHeight = height / rows;
            for (int i = 0; i < rows - 1; i++){
                canvas.drawLine(0, tabHeight * (i + 1), width, tabHeight * (i + 1), paint);
            }
        }
        // 画竖线
        if (cols > 1){
            int tabWidth = width / cols;
            for (int i = 0; i < cols - 1; i++){
                canvas.drawLine(tabWidth * (i + 1), 0, tabWidth * (i + 1) , height, paint);
            }
        }
        HH_PicUtils.BitmapSaveFile(bitmap, path);
    }

    public static void MadeLinePic(String path, int width, int height, HH_T_RGB getColor2, int rotation) {
        Bitmap bitmap = Bitmap.createBitmap(width, height,
                Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawRGB(getColor2.getR(), getColor2.getG(), getColor2.getB());
        bitmap = HH_PicUtils.rotationBitmap(bitmap, rotation);
        HH_PicUtils.BitmapSaveFile(bitmap, path);
    }


    private static String GetConfigPicInfo(String url){
        OkHttpClient okHttpClient=new OkHttpClient.Builder()
                .connectTimeout(50, TimeUnit.SECONDS)
                .readTimeout(50,TimeUnit.SECONDS)
                .writeTimeout(50,TimeUnit.SECONDS)
                .build();
        //创建请求
        Request request= null;
        try {
            request = new Request.Builder()
                    .url( new URL(url) )
                    .get() //GET方式用
                    .build();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        //同步
        Response response= null;
        try {
            //同步请求数据
            response = okHttpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                String s1 = response.body().string();

                return s1;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return  "";
    }


    private static void downFile(HH_T_SystemParams tp, String downloadUrl, String savePath) {


        final CountDownLatch latch = new CountDownLatch(1);

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(downloadUrl)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                HH_Logging.i(TAG, tp, "下载失败1");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.body() == null) {
                    HH_Logging.i(TAG, tp, "下载失败2");
                    return;
                }
                InputStream is = null;
                FileOutputStream fos = null;
                byte[] buff = new byte[2048];
                int len;
                try {
                    is = response.body().byteStream();

                    File updateFile = new File(savePath);
                    if (!updateFile.exists()) {
                        updateFile.createNewFile();
                    } else {
                        updateFile.delete();
                        updateFile.createNewFile(); //重新创建一下，防止没有覆盖
                    }

                    fos = new FileOutputStream(updateFile);
                    long total = response.body().contentLength();
                    //  contentLength=total;
                    long sum = 0;
                    while ((len = is.read(buff)) != -1) {
                        fos.write(buff, 0, len);
                        sum += len;
                    }
                    fos.flush();

                    latch.countDown();

                } catch (Exception e) {
                    e.printStackTrace();
                    HH_Logging.i(TAG, tp, "下载失败3");
                } finally {
                    try {
                        if (is != null)
                            is.close();
                        if (fos != null)
                            fos.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        try {
            latch.await();//阻塞异步请求，等待接口回调，同步
        } catch (InterruptedException e) {
        }

        return;
    }

    public static List<Integer> GetPrismData(String dataPath) {
        List<Integer> list = new ArrayList<>();

        if (!HH_FileUtil.IsExists(dataPath))
            return list;

        String sFileInfo = HH_FileUtil.ReadFile(null, dataPath);
        if (sFileInfo == null)
            return list;

        sFileInfo = sFileInfo.replaceAll("0x", "");

        String sOne[] = sFileInfo.split(", ");
        if (sOne == null)
            return list;

        for (int i = 0; i < sOne.length; i++){
            byte b[] = HH_HexUtil.hexStringToBytes(sOne[i]);
            if (b != null && b.length == 1){
                list.add((int)b[0]);
            }
        }

        return list;
    }

    private static File findSDCardRoot(File externalFilesDir) {
        File parent;
        boolean equals = (Objects.requireNonNull(parent = externalFilesDir.getParentFile())).getName().equals("0");
        if (!equals) {
            return findSDCardRoot(parent);
        } else {
            return parent;
        }
    }

    public static File getExternalStorageDirectory(Context ctx){
        // 这个过时了
        //String rootDataDir2 = Environment.getExternalStorageDirectory().getPath();

        // 调用
        File sdCardRoot = findSDCardRoot(ctx.getExternalFilesDir(null));
        if (sdCardRoot == null)
            return null;

        return sdCardRoot;
    }

    public static HH_EnumDeviceColorType MadeColorType(String deviceColor) {
        if (deviceColor == null)
            return HH_EnumDeviceColorType.BLACK_WHITE_0;

        if (HH_CharUtil.Strcmp(deviceColor, "BWRYGBO", true)) {
            return (HH_EnumDeviceColorType.N_COLOR_4);
        } else if (HH_CharUtil.Strcmp(deviceColor, "BWRY", true)) {
            return (HH_EnumDeviceColorType.BLACK_WHITE_RED_YELLOW_3);
        } else if (HH_CharUtil.Strcmp(deviceColor, "BWY", true)) {
            return (HH_EnumDeviceColorType.BLACK_WHITE_YELLOW_1);
        } else if (HH_CharUtil.Strcmp(deviceColor, "BWR", true)) {
            return (HH_EnumDeviceColorType.BLACK_WHITE_RED_2);
        } else if (HH_CharUtil.Strcmp(deviceColor, "BW", true)) {
            return (HH_EnumDeviceColorType.BLACK_WHITE_0);
        } else if (HH_CharUtil.Strcmp(deviceColor, "E6", true)) {
            return (HH_EnumDeviceColorType.E6_5);
        }
        return HH_EnumDeviceColorType.BLACK_WHITE_0;
    }

    public static int GetBatteryPercentage(Context ctx) {
        Intent batteryIntent = ctx.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
        int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
        int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
        int batteryPercentage = -1;
        if (level != -1 && scale != -1) {
            batteryPercentage = (int) (((float) level / (float) scale) * 100.0f);
        }
        return batteryPercentage;
    }

    public static int GetEslDeviceTypeFormColor(String color) {
        if (color == null)
            return -1;

        if (HH_CharUtil.Strcmp(color, "BW", true)){
            return 0;
        }
        if (HH_CharUtil.Strcmp(color, "BWR", true)){
            return 1;
        }
        if (HH_CharUtil.Strcmp(color, "BWY", true)){
            return 1;
        }
        if (HH_CharUtil.Strcmp(color, "BWRY", true)){
            return 3;
        }

       return -1;
    }

    public interface ResultCallBackPerm {
        public void callback();
    }

    public static void OpenPerm(FragmentActivity ctx, final ResultCallBackPerm resultCallBack) {
        PermissionX.init(ctx)
                .permissions(
                        Manifest.permission.BLUETOOTH,
                        Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA)
                .explainReasonBeforeRequest()
                .onExplainRequestReason((scope, deniedList, beforeRequest) -> scope.showRequestReasonDialog(deniedList,
                        ctx.getString(R.string.strID_548),
                        ctx.getString(R.string.strID_181),
                        ctx.getString(R.string.strID_384)))
                .request(new RequestCallback() {
                    @Override
                    public void onResult(boolean allGranted, @NonNull List<String> grantedList, @NonNull List<String> deniedList) {
                        resultCallBack.callback();
                    }
                });
    }

    public static String GetAppTempFilesPath(String appPath) {
        String rootDataDir = Environment.getExternalStorageDirectory().getPath();
        String savePath = String.format("%s%s%s%s",
                rootDataDir,
                File.separator,
                appPath,
                File.separator);
        HH_FileUtil.CreateFolder(savePath);

        return savePath;
    }


    public static List<String> InitFontSizeInfo(){
        List<String> list = new ArrayList<>();
        for (int i = 2; i < 20; i += 2)
            list.add(String.format("%d", i));
        for (int i = 20; i < 40; i += 4)
            list.add(String.format("%d", i));
        for (int i = 40; i < 80; i += 8)
            list.add(String.format("%d", i));
        for (int i = 80; i < 120; i += 10)
            list.add(String.format("%d", i));
        for (int i = 120; i < 160; i += 12)
            list.add(String.format("%d", i));
        return list;
    }

    public static List<HH_T_RGB> InitFontColorInfo(Context ctx){
        List<HH_T_RGB> list = new ArrayList<>();
        list.add(new HH_T_RGB(0, 0, 0, ctx));
        list.add(new HH_T_RGB(255, 255, 255, ctx));
        list.add(new HH_T_RGB(255, 0, 0, ctx));
        list.add(new HH_T_RGB(0, 255, 0, ctx));
        list.add(new HH_T_RGB(0, 0, 255, ctx));
        list.add(new HH_T_RGB(255, 255, 0, ctx));
        list.add(new HH_T_RGB(255, 127, 0, ctx));
        return list;
    }

    public static List<HH_T_RGB> InitBKGColorInfo(Context ctx){
        List<HH_T_RGB> list = new ArrayList<>();
        list.add(new HH_T_RGB(0, 0, 0, ctx));
        list.add(new HH_T_RGB(255, 255, 255, ctx));
        list.add(new HH_T_RGB(255, 0, 0, ctx));
        list.add(new HH_T_RGB(0, 255, 0, ctx));
        list.add(new HH_T_RGB(0, 0, 255, ctx));
        list.add(new HH_T_RGB(255, 255, 0, ctx));
        list.add(new HH_T_RGB(255, 127, 0, ctx));
        list.add(new HH_T_RGB(-1, -1, -1, ctx));
        return list;
    }

    public static List<String> InitFontNameInfo(){
        List<String> list = new ArrayList<>();
        list.add("DEFAULT"); //常规字体类型
        list.add("DEFAULT_BOLD"); //黑体字体类型
        list.add("MONOSPACE"); //等宽字体类型
        list.add("SANS_SERIF"); //sans serif字体类型
        list.add("SERIF"); //serif字体类型
        return list;
    }


    public static List<HH_EnumTextAlgin> InitFontAlginInfo(){
        List<HH_EnumTextAlgin> list = new ArrayList<>();
        list.add(HH_EnumTextAlgin.LEFT);//左
        list.add(HH_EnumTextAlgin.CENTER);//中
        list.add(HH_EnumTextAlgin.RIGHT);//右
        return list;
    }

    public static List<HH_T_DeviceInfo> InitDeviceInfo(){
        List<HH_T_DeviceInfo> list = new ArrayList<>();
        list.add(new HH_T_DeviceInfo(1024, 576));
        list.add(new HH_T_DeviceInfo(800, 480));
        list.add(new HH_T_DeviceInfo(880, 528));
        list.add(new HH_T_DeviceInfo(960, 640));
        list.add(new HH_T_DeviceInfo(750, 200));
        list.add(new HH_T_DeviceInfo(680, 384));
        list.add(new HH_T_DeviceInfo(480, 240));
        list.add(new HH_T_DeviceInfo(400, 600));
        list.add(new HH_T_DeviceInfo(400, 300));
        list.add(new HH_T_DeviceInfo(384, 168));
        list.add(new HH_T_DeviceInfo(360, 184));
        list.add(new HH_T_DeviceInfo(240, 416));
        list.add(new HH_T_DeviceInfo(168, 384));
        list.add(new HH_T_DeviceInfo(122, 250));
        list.add(new HH_T_DeviceInfo(184, 360));
        list.add(new HH_T_DeviceInfo(128, 296));
        list.add(new HH_T_DeviceInfo(152, 296));
        list.add(new HH_T_DeviceInfo(152, 152));
        list.add(new HH_T_DeviceInfo(200, 300));
        list.add(new HH_T_DeviceInfo(200, 200));
        return list;
    }


    public static List<HH_T_DeviceColorType> InitDeviceColorTypeInfo(Context ctx){
        List<HH_T_DeviceColorType> list = new ArrayList<>();
        list.add(new HH_T_DeviceColorType(HH_EnumDeviceColorType.BLACK_WHITE_0, ctx.getString(R.string.strID_218)));
        list.add(new HH_T_DeviceColorType(HH_EnumDeviceColorType.BLACK_WHITE_YELLOW_1, ctx.getString(R.string.strID_219)));
        list.add(new HH_T_DeviceColorType(HH_EnumDeviceColorType.BLACK_WHITE_RED_2, ctx.getString(R.string.strID_220)));
        list.add(new HH_T_DeviceColorType(HH_EnumDeviceColorType.BLACK_WHITE_RED_YELLOW_3, ctx.getString(R.string.strID_221)));
        list.add(new HH_T_DeviceColorType(HH_EnumDeviceColorType.N_COLOR_4, ctx.getString(R.string.strID_222)));
        list.add(new HH_T_DeviceColorType(HH_EnumDeviceColorType.E6_5, ctx.getString(R.string.strID_443)));
        return list;
    }



    public static void downPic(String downloadUrl, String savePath) {
        final CountDownLatch latch = new CountDownLatch(1);

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(downloadUrl)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.body() == null) {

                    return;
                }
                InputStream is = null;
                FileOutputStream fos = null;
                byte[] buff = new byte[2048];
                int len;
                try {
                    is = response.body().byteStream();

                    File updateFile = new File(savePath);
                    if (!updateFile.exists()) {
                        updateFile.createNewFile();
                    } else {
                        updateFile.delete();
                        updateFile.createNewFile(); //重新创建一下，防止没有覆盖
                    }

                    fos = new FileOutputStream(updateFile);
                    long total = response.body().contentLength();
                    //  contentLength=total;
                    long sum = 0;
                    while ((len = is.read(buff)) != -1) {
                        fos.write(buff, 0, len);
                        sum += len;
                    }
                    fos.flush();

                    latch.countDown();

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (is != null)
                            is.close();
                        if (fos != null)
                            fos.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        try {
            latch.await();//阻塞异步请求，等待接口回调，同步
        } catch (InterruptedException e) {
        }

        return;
    }



    // 添加默认模板
    public static List<HH_T_PasterInfo> GePasterInfosDefault(Application application, Context context) {
        List<HH_T_PasterInfo> list = new ArrayList<>();

        // 先通过接口 获取贴纸类型
        list = GetPasterType();

        // 根据ID设置贴纸保存地址
        SetPasterSavePath(application, list);

        // 下载图片
        DownLoadPasterInfo(list);


        return list;

    }



    public static List<HH_T_PasterInfo> GetPasterType(){
        String jsonData = GetConfigPicInfo("http://api.seekink.cn:8092/prod-api/api/v1/stickerType/list");
        List<HH_T_PasterInfo> list = new ArrayList<>();
        try {
            JSONObject object = new JSONObject(jsonData);
            int code = object.getInt("code");
            if (code == 200){
                JSONArray rows = object.getJSONArray("rows");
                for (int n = 0; n < rows.length(); n++){
                    JSONObject js = rows.getJSONObject(n);
                    String id = js.getString("id");
                    String nameCn = js.getString("nameCn");
                    if (nameCn == null || nameCn.length() <= 0)
                        nameCn = "空";
                    String nameEn = js.getString("nameEn");
                    if (nameEn == null || nameEn.length() <= 0)
                        nameEn = "null";
                    if (id != null && id.length() > 0){
                        list.add(new HH_T_PasterInfo(nameCn, nameEn, id, ""));
                    }
                }

                return list;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return list;
    }


    private static void SetPasterSavePath(Application application, List<HH_T_PasterInfo> list) {
        if (list == null)
            return;

        String pathPasterRoot = HH_SystemUtil.GetAppRootFolder(application) + "Paster" + File.separator;
        for (int i = 0; i < list.size(); i++){
            String path = pathPasterRoot + list.get(i).getId();
            HH_FileUtil.CreateFolder(path);
            list.get(i).setPath(path);
        }
    }


    private static void DownLoadPasterInfo(List<HH_T_PasterInfo> list) {

        if (list != null){
            for (int i = 0; i < list.size(); i++){
                String url = String.format("http://api.seekink.cn:8092/prod-api/api/v1/sticker/list?stickerType=%s", list.get(i).getId());
                String jsonData = GetConfigPicInfo(url);

                List <String> pics = new ArrayList<>();

                try {
                    JSONObject object = new JSONObject(jsonData);
                    int code = object.getInt("code");
                    if (code == 200){
                        JSONArray rows = object.getJSONArray("rows");
                        for (int n = 0; n < rows.length(); n++){
                            JSONObject js = rows.getJSONObject(n);
                            String fileUrl = js.getString("fileUrl");
                            String id = js.getString("id");
                            if (fileUrl != null && fileUrl.length() > 0 && id != null && id.length() > 0){
                                String []array = fileUrl.split("\\.");
                                if (array != null && array.length > 0){
                                    String ext = array[array.length - 1];
                                    String file = list.get(i).getPath() + File.separator + id + "." + ext;
                                    if (!HH_FileUtil.IsExists(file)){
                                        // 下载文件
                                        downPic(fileUrl, file);
                                    } else {
                                    }

                                    if (HH_FileUtil.IsExists(file)){
                                        pics.add(file);
                                    }
                                }
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                list.get(i).setPics(pics);
            }
        }
    }


    // 添加默认模板
    public static List<HH_T_DeviceModel> GetDeviceModelsDefault(Context context,
                                                                List<HH_T_DeviceColorType> listDeviceColorType,
                                                                boolean useLogin,
                                                                String deviceModelSavePath ) {

        HashMap<String, HH_T_ThemeList> theme = new HashMap<>();
        try {
            theme = HH_ProtocolHttp.GetThemeList(context, "", 0);
        } catch (IOException e) {
            e.printStackTrace();
        }

        List<HH_T_DeviceModel> list = GetServerModelInfos(context, listDeviceColorType, useLogin, deviceModelSavePath);

        if (list != null && theme != null){
            for (int i = 0; i < list.size(); i++){
                String type = list.get(i).getModelType();
                list.get(i).setNameChinese(theme.get(type).getNameCn());
                list.get(i).setNameEnglish(theme.get(type).getNameEn());
            }
        }

        return list;
    }

    public static HH_EnumDeviceColorType GetDeviceColorFormStr(String color) {
        if (color == null || color.length() <= 0)
            return HH_EnumDeviceColorType.NONE;

        if (HH_CharUtil.Strcmp(color, "BW", true))
            return HH_EnumDeviceColorType.BLACK_WHITE_0;
        else if (HH_CharUtil.Strcmp(color, "BWY", true))
            return HH_EnumDeviceColorType.BLACK_WHITE_YELLOW_1;
        else if (HH_CharUtil.Strcmp(color, "BWR", true))
            return HH_EnumDeviceColorType.BLACK_WHITE_RED_2;
        else if (HH_CharUtil.Strcmp(color, "BWRY", true))
            return HH_EnumDeviceColorType.BLACK_WHITE_RED_YELLOW_3;
        else if (HH_CharUtil.Strcmp(color, "BWRYGBO", true))
            return HH_EnumDeviceColorType.N_COLOR_4;
        else if (HH_CharUtil.Strcmp(color, "BWRYGB", true))
            return HH_EnumDeviceColorType.E6_5;
        else if (HH_CharUtil.Strcmp(color, "N_COLOR_16_6", true))
            return HH_EnumDeviceColorType.N_COLOR_16_6;
        else
            return HH_EnumDeviceColorType.NONE;
    }


    // 从服务器获取信息
    private static List<HH_T_DeviceModel> GetServerModelInfos(Context ctx,
                                                              List<HH_T_DeviceColorType> listDeviceColorType,
                                                              boolean useLogin,
                                                              String deviceModelSavePath){
        List<HH_T_DeviceModel> list = new ArrayList<>();

        // 获取主题列表
        HH_T_LoginInfo tl = HH_INILoginInfo.Get(ctx);

        if (useLogin){
            if (tl.getToken() == null)
                return list;
        }

        try {

            // 获取素材列表
            List <HH_T_Material> materialList = HH_ProtocolHttp.GetMaterialList(ctx, tl.getToken(), 0, deviceModelSavePath);

            if (materialList != null){
                for (int i = 0; i < materialList.size(); i++){
                    list.add(new HH_T_DeviceModel(materialList.get(i).getColor(), materialList.get(i).getThemeName(), materialList.get(i).getThemeID(),
                            materialList.get(i).getThemeName(),
                            materialList.get(i).getThemeName(),
                            100,
                            100,
                            materialList.get(i).getFileUrl(),
                            materialList.get(i).getFileSavePath(),
                            materialList.get(i).getSize()));
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }


    // 写入首次使用参数
    public static void WriteNewBieInfo(Application api, boolean bFirst){
        String packageName = api.getPackageName();
        packageName = packageName.replaceAll("\\.", "_");
        String rootDataDir = Environment.getExternalStorageDirectory().getPath();
        rootDataDir = rootDataDir + File.separator + "." + packageName;
        HH_FileUtil.CreateFolder(rootDataDir);
        rootDataDir = rootDataDir + File.separator + "newbie.txt";

        if (bFirst){
            HH_FileUtil.WriteFile(rootDataDir, "0", false);
        } else {
            HH_FileUtil.WriteFile(rootDataDir, "1", false);
        }
    }


    public static String GetCacheInfo(Application api, String modelSavePath) {

        // 这个是不能删除的模板文件夹
        double dSizeTemplate = HH_FileSizeUtil.getFileOrFilesSize(modelSavePath, HH_FileSizeUtil.SIZETYPE_B);

        // 这个是不能删除的绑定的设备文件夹
        double dSizeBindDevices = HH_FileSizeUtil.getFileOrFilesSize(HH_INIBindDeviceInfo.GetBindDeviceFolder(api), HH_FileSizeUtil.SIZETYPE_B);

        // 这个是APP的数据文件夹
        double dSizeApp = HH_FileSizeUtil.getFileOrFilesSize(GetAppRootFolder(api), HH_FileSizeUtil.SIZETYPE_B);

        double dCacheUseDel = dSizeApp - dSizeBindDevices - dSizeTemplate;

        if (dCacheUseDel > 0.0)
            return HH_FileSizeUtil.FormetFileSize((long) dCacheUseDel);
        else
            return "0.0";
    }


    // 文件类型，1图片，2XLS
    public static String GetSelectPicPath(Context ctx, Intent data, int type, int fileType) {
        if (data == null)
            return "";

        if (type == 0) {
            Uri uri = data.getData();
            // 獲取真實路徑獲取
            HH_T_DIR_INFO diSrc = HH_SystemUtil.GetPicPath(ctx, uri);
            if (diSrc.getExtN() != null && diSrc.getExtN().length() > 0) {
                // 這是正常的有擴展名的情況
                if (fileType == 1) {
                    if (HH_CharUtil.Strcmp(diSrc.getExtN(), "bmp", true) || HH_CharUtil.Strcmp(diSrc.getExtN(), "jpg", true) || HH_CharUtil.Strcmp(diSrc.getExtN(), "jpeg", true) || HH_CharUtil.Strcmp(diSrc.getExtN(), "png", true)) {
                        return HH_UriUtils.getFileAbsolutePath(ctx, uri);
                    }
                } else if (fileType == 2) {
                    if (HH_CharUtil.Strcmp(diSrc.getExtN(), "xls", true) || HH_CharUtil.Strcmp(diSrc.getExtN(), "xlsx", true)) {
                        return HH_UriUtils.getFileAbsolutePath(ctx, uri);
                    }
                } else if (fileType == 3) {
                    if (HH_CharUtil.Strcmp(diSrc.getExtN(), "zip", true) || HH_CharUtil.Strcmp(diSrc.getExtN(), "rar", true)) {
                        return HH_UriUtils.getFileAbsolutePath(ctx, uri);
                    }
                }
            }
        } else if (type == 1) {
            List<String> listPath = data.getStringArrayListExtra("paths");
            if (listPath != null && listPath.size() == 1) {

                HH_T_DIR_INFO diSrc;
                diSrc = HH_FileUtil.GetCurFileInfo(listPath.get(0));
                if (diSrc.getExtN() != null && diSrc.getExtN().length() > 0) {
                    // 這是正常的有擴展名的情況
                    if (fileType == 1) {
                        if (HH_CharUtil.Strcmp(diSrc.getExtN(), "bmp", true) || HH_CharUtil.Strcmp(diSrc.getExtN(), "jpg", true) || HH_CharUtil.Strcmp(diSrc.getExtN(), "jpeg", true) || HH_CharUtil.Strcmp(diSrc.getExtN(), "png", true)) {
                            return listPath.get(0);
                        }
                    } else if (fileType == 2) {
                        if (HH_CharUtil.Strcmp(diSrc.getExtN(), "xls", true) || HH_CharUtil.Strcmp(diSrc.getExtN(), "xlsx", true)) {
                            return listPath.get(0);
                        }
                    }
                }
            }
        } else if (type == 2) {
            List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
            if (selectList != null && selectList.size() > 0) {
                return selectList.get(0).getRealPath();
            }
        }

        return "";
    }


    // 将BMP文件保存在临时目录
    public static String SaveTempFileToSD(Application api, Bitmap bt) {
        if (bt == null)
            return "";

        String rootDataDir = GetAppRootFolder(api);
        String savePath = String.format("%s%d%s%d%s%s",
                rootDataDir,
                bt.getWidth(),
                "_",
                bt.getHeight(),
                File.separator,
                HH_TimeUtil.GetCurrentSystemTimeD());
        HH_FileUtil.CreateFolder(savePath);

        HH_PicUtils.BitmapSaveFile(bt, savePath + File.separator + HH_TimeUtil.GetCurrentSystemTimeF() + ".bmp");

        return savePath + File.separator + HH_TimeUtil.GetCurrentSystemTimeF() + ".bmp";
    }

    // 设置控件粗体
    public static void setTextBold(TextView textView, boolean isBold) {
        try {
            if(textView != null) {
                Paint paint = textView.getPaint();
                if(paint != null) {
                    paint.setFakeBoldText(isBold);
                }
            }
        } catch (Throwable var3) {
        }
    }

    public static String getDeviceModel() {
        String marketName = getSystemProperty("ro.product.marketname");
        if (marketName != null && !marketName.isEmpty() && !"unknown".equals(marketName)) {
            return marketName;
        } else {
            return Build.MODEL;
        }
    }

    public static String getSystemProperty(String key) {
        try {
            Class<?> c = Class.forName("android.os.SystemProperties");
            Method get = c.getMethod("get", String.class, String.class);
            return (String) get.invoke(null, key, "unknown");
        } catch (Exception e) {
            return "unknown";
        }
    }

    public static String GetPhoneModel(){
        return getDeviceModel().toLowerCase();
    }

    public static byte[] parseTextRecord(NdefRecord ndefRecord) {

        //判断TNF
        if (ndefRecord.getTnf() != NdefRecord.TNF_WELL_KNOWN) {
            return null;
        }
        //判断可变的长度的类型
        if (!Arrays.equals(ndefRecord.getType(), NdefRecord.RTD_TEXT)) {
            return null;
        }
        try {
            //获得字节数组，然后进行分析
            byte[] payload = ndefRecord.getPayload();
            return payload;
        } catch (Exception e) {
            throw new IllegalArgumentException();
        }
    }

    public static String ColorChange_XT_To_ESL(HH_EnumDeviceColorType color){
        switch (color){
            case BLACK_WHITE_0:
                return "BW";
            case BLACK_WHITE_YELLOW_1:
                return "BWY";
            case BLACK_WHITE_RED_2:
                return "BWR";
            case BLACK_WHITE_RED_YELLOW_3:
                return "BWRY";
        }

        // 暂时就这4个
        return "";
    }

    public static HH_EnumDeviceColorType ColorChange_ESL_To_XT(String color){
       if (color == null || color.length() <= 0)
           return HH_EnumDeviceColorType.BLACK_WHITE_0;

       if (HH_CharUtil.Strcmp(color, "BW", true))
           return HH_EnumDeviceColorType.BLACK_WHITE_0;
        if (HH_CharUtil.Strcmp(color, "BWY", true))
            return HH_EnumDeviceColorType.BLACK_WHITE_YELLOW_1;
        if (HH_CharUtil.Strcmp(color, "BWR", true))
            return HH_EnumDeviceColorType.BLACK_WHITE_RED_2;
        if (HH_CharUtil.Strcmp(color, "BWRY", true))
            return HH_EnumDeviceColorType.BLACK_WHITE_RED_YELLOW_3;

        return HH_EnumDeviceColorType.BLACK_WHITE_0;
    }
}